import React, { Component} from 'react'
import PropTypes from "prop-types"
import { Upload, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { reqDeleteImg } from '@/api';
import { BASE_IMG_URL } from '@/utils/constant';
/**
 * 用于图片上传的组件
 */

const getBase64 = (file) =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });

export default class PicturesWall extends Component {
    static propTypes={
        imgs:PropTypes.array
    }
    constructor(props) {
        super(props)
        let fileList=[]

        //如果传入了imgs属性
        const {imgs}=this.props
        if(imgs&&imgs.length>0){
            fileList=imgs.map((img,index)=>({
                uid:-index,
                name:img,
                status:'done',
                url:BASE_IMG_URL+img
            }))
        } 
        //指定初始状态
        this.state = {
            previewVisible: false,  //标识是否显示大图预览界面
            previewImage: '',  //大图的地址
            fileList,  //所有已上传图片的数组
        }
    }
    
    
    //隐藏modal
    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {   //显示指定的file对应的大图
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
        });
    };

    //fileList: 所有图片的上传图片的数组
    //file: 表示当前操作的图片文件
    handleChange = async({ file,fileList }) => {
       
        //一旦上传成功将当前的file的信息修正(name,url)
        if(file.status==='done'){
            const result=file.response;   //{status:0,data:{name:'xxx',url:'图片地址'}}
            if(result.status===0){
                message.success("图片上传成功")
                const {name,url}=result.data;
                file=fileList[fileList.length-1]
                file.name=name;
                file.url=url
            }else{
                message.error("图片上传失败")
            }
        }else if(file.status==='removed'){  //删除图片
            const result=await reqDeleteImg(file.name)
            if(result.data.status===0){
                message.success("删除图片成功！")
            }else{
                message.error("删除图片失败！")
            }
        }
        //在操作(上传/删除)过程中更新fileList状态
        this.setState({ fileList })
    };
    //获取所有文件名的数组
    getImgs =()=>{
        return this.state.fileList.map(file=>file.name)
    }

    render() {
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div>Upload</div>
            </div>
        );
        return (
            <div>
                <Upload
                    action="/manage/img/upload"   //上传图片的接口地址
                    accept='image/*'  //接受值为图片类型
                    name='image'  //请求参数名
                    listType="picture-card"  //上传图片的样式--照片墙
                    fileList={fileList}   //所有已上传图片的对象数组列表
                    onPreview={this.handlePreview}   //调用指定的预览大图回调函数
                    onChange={this.handleChange}>
                    {fileList.length >= 8 ? null : uploadButton}
                </Upload>
                <Modal open={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}
